package com.plan.controller.card;

import com.plan.base.constant.BaseCode;
import com.plan.base.constant.Constant;
import com.plan.base.entity.Result;
import com.plan.base.util.DateUtil;
import com.plan.controller.card.request.PointLogPageListReq;
import com.plan.controller.user.response.UserVO;
import com.plan.entity.card.PointLog;
import com.plan.service.card.PointLogService;
import com.plan.service.card.TeamService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 积分历史
 * 金币明细
 *
 * @author zcl
 */
@RestController
@RequestMapping("pointLog/")
public class PointLogController {
    @Resource
    private TeamService teamService;
    @Resource
    private PointLogService pointLogService;

    /**
     * 金币明细列表
     */
    @PostMapping(value = "list")
    public Result<List<PointLog>> list(@RequestBody PointLogPageListReq req, HttpServletRequest httpRequest) {
        if (req.getTeamId() == null || req.getCardId() == null) {
            return Result.fail(BaseCode.PARAM_ERROR);
        }
        Date startLimit = DateUtil.addDays(new Date(), -30);
        if (req.getStartTime() == null) {
            req.setStartTime(startLimit);
        }
        if (req.getEndTime() == null) {
            req.setEndTime(new Date());
        }
        if (req.getStartTime().before(startLimit)) {
            return Result.fail(BaseCode.PARAM_ERROR);
        }
        req.setPageSize(20);
        UserVO user = (UserVO) httpRequest.getAttribute(Constant.USER_KEY);
        if (!teamService.isUserInTeam(req.getTeamId(), user.getId())) {
            return Result.fail(BaseCode.ILLEGAL_OPERATION);
        }
        List<PointLog> list = pointLogService.getPointLogPageList(req);
        return Result.ok(list);
    }
}
